//
//  sureOrderViewController.m
//  YuErmuYing
//
//  Created by Tiancheng on 16/8/23.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "sureOrderViewController.h"
#import "activityOrderViewController.h"
#import "HttpRequest.h"
//#import "nextActivityModel.h"
#import "buyNSObject.h"
#import "Macros.h"
#import "TCLYUser.h"

#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "homeViewController.h"
//传参数用的
#import "activityOrder.h"

@interface sureOrderViewController ()
@property (weak, nonatomic) IBOutlet UIView *headerView;
//账号
@property (weak, nonatomic) IBOutlet UILabel *accountlLabel;
//钱
@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;
//支付宝对号01
@property (weak, nonatomic) IBOutlet UIImageView *tickImageView01;
//微信对号02
@property (weak, nonatomic) IBOutlet UIImageView *tickImageView02;
//钱包对号03
@property (weak, nonatomic) IBOutlet UIImageView *tickImageView03;

//点击支付宝那个view
@property (weak, nonatomic) IBOutlet UIView *view01;
//点击微信那个view
@property (weak, nonatomic) IBOutlet UIView *view02;
//点击钱包那个view
@property (weak, nonatomic) IBOutlet UIView *view03;

//确认付款
@property (weak, nonatomic) IBOutlet UIButton *buyBtn;
//接口地址
@property(nonatomic,copy)NSString *urlString1;
//
@property(nonatomic,copy)NSMutableArray *json_Array1;

@property(nonatomic,copy)NSString *ticket_IDString;

@property(nonatomic,assign)int payNum;
//
@property(nonatomic,assign)int num;
@end

@implementation sureOrderViewController
@synthesize json_Array1,payNum,num;
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=YES;
    self.tabBarController.tabBar.hidden=YES;

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    NSString *str=[userDefaults objectForKey:@"ALiOrWeiXin"];
    if (str==NULL||[str isEqualToString:@"1"])
    {
//        self.tickImageView01.hidden=NO;
//        self.tickImageView02.hidden=YES;
//        self.tickImageView03.hidden=YES;
//        NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
//        [userDefaults setValue:@"1" forKey:@"ALiOrWeiXin"];
        //view03 钱包
        self.view03.tag=1;
        payNum=(int)self.view03.tag;
        num=payNum;
        self.tickImageView01.hidden=YES;
        self.tickImageView02.hidden=YES;
        self.tickImageView03.hidden=NO;
//        NSLog(@"钱包");
        num=1;
    }
    else if ([str isEqualToString:@"2"])
    {
        //view02 微信
//        self.view02.tag=2;
//        payNum=(int)self.view02.tag;

        self.tickImageView01.hidden=YES;
        self.tickImageView02.hidden=NO;
        self.tickImageView03.hidden=YES;
//        NSLog(@"微信");
        num=2;
    }
    else if ([str isEqualToString:@"3"])
    {
//        self.tickImageView01.hidden=YES;
//        self.tickImageView02.hidden=YES;
//        self.tickImageView03.hidden=NO;
        //view01 支付宝
//        self.view01.tag=3;
//        payNum=(int)self.view03.tag;
        self.tickImageView01.hidden=NO;
        self.tickImageView02.hidden=YES;
        self.tickImageView03.hidden=YES;
        num=3;
//        NSLog(@"支付宝");

    }
    //更改背景色
    [self changeBackGroundColor];
//    [self updateDataFromNet];
    [self changeAccountAndMoney];
    //给支付宝,微信增加手势
    [self addUITapGestureRecognizer];
    //发送通知进行跳转页面
    NSNotificationCenter *notification=[NSNotificationCenter defaultCenter];
//    [notification postNotificationName:@"AliPay" object:nil];
    [notification addObserver:self selector:@selector(goBackMainView) name:@"AliPay" object:nil];
    
}
-(void)changeBackGroundColor
{
    self.view.backgroundColor=[UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1.0];
    self.headerView.backgroundColor=[UIColor colorWithRed:244/255.0 green:143/255.0 blue:177/255.0 alpha:1.0];
    self.buyBtn.backgroundColor=[UIColor colorWithRed:216/255.0 green:26/255.0 blue:96/255.0 alpha:1.0];
}
-(void)changeAccountAndMoney
{
   buyNSObject *bn=[buyNSObject shardeManager];
    self.moneyLabel.text=bn.all_price;
    self.accountlLabel.text=bn.user_tel;

}
//-(void)updateDataFromNet
//{
//    nextActivityModel*nam=[nextActivityModel shardeManager];
//    self.ticket_IDString=nam.ticket_id;
//    self.urlString1=[NSString stringWithFormat:@"http://112.74.114.1/parenting/Admin/ActiveInterface/order"];
//    //?user_id=1&ticket_id=38
//    NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
//    parameters[@"user_id"]=@"1";
//    parameters[@"ticket_id"]=self.ticket_IDString;
//    HttpRequest *httpRequest=[HttpRequest sharedInstance];
//    [httpRequest postWithURLString:self.urlString1 parameters:parameters success:^(id responseObject)
//     {
//         id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
//         //获取数组
//         json_Array1=[json objectForKey:@"data"];
//         if (json_Array1.count>0)
//         {
//
//         }
//                    NSLog(@"json=%@",json);
//     } failure:^(NSError *error) {
//         NSLog(@"error=%@",error);
//     }];
//}

-(void)addUITapGestureRecognizer
{
    //view01 支付宝
    self.view01.tag=3;
    //view02 微信
    self.view02.tag=2;
    //view03 钱包
    self.view03.tag=1;

    UITapGestureRecognizer *tap1=[[UITapGestureRecognizer  alloc ] initWithTarget:self action : @selector (onCick1:)];
    UITapGestureRecognizer *tap2=[[UITapGestureRecognizer  alloc ] initWithTarget:self action : @selector (onCick2:)];
    UITapGestureRecognizer *tap3=[[UITapGestureRecognizer  alloc ] initWithTarget:self action : @selector (onCick3:)];
    self.view01.userInteractionEnabled = YES;
    [self.view01 addGestureRecognizer:tap1];
    self.view02.userInteractionEnabled = YES;
    [self.view02 addGestureRecognizer:tap2];
    self.view03.userInteractionEnabled = YES;
    [self.view03 addGestureRecognizer:tap3];

}
//支付宝view
-(void)onCick1:(UITapGestureRecognizer *)sender
{
    //支付宝
    num=(int)sender.view.tag;
    payNum=num;
     if (num==3)
    {
        NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
        [userDefaults setValue:@"1" forKey:@"ALiOrWeiXin"];
//        self.tickImageView01.hidden=NO;
//        self.tickImageView02.hidden=YES;
//        self.tickImageView03.hidden=YES;
        
        self.tickImageView01.hidden=NO;
        self.tickImageView02.hidden=YES;
        self.tickImageView03.hidden=YES;
//        NSLog(@"支付宝");
    }
}
//微信view
-(void)onCick2:(UITapGestureRecognizer *)sender
{
    //微信
     num=(int)sender.view.tag;
    payNum=num;
//    NSLog(@"payNum02=%d",payNum);

     if (num==2)
    {
        NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
        [userDefaults setValue:@"2" forKey:@"ALiOrWeiXin"];
        self.tickImageView01.hidden=YES;
        self.tickImageView02.hidden=NO;
        self.tickImageView03.hidden=YES;
//        NSLog(@"微信");

    }
}
//钱包view
-(void)onCick3:(UITapGestureRecognizer *)sender
{
    num=(int)sender.view.tag;
    payNum=num;
//    NSLog(@"payNum03=%d",payNum);

    if (num==1)
    {
        NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
        [userDefaults setValue:@"3" forKey:@"ALiOrWeiXin"];
        self.tickImageView01.hidden=YES;
        self.tickImageView02.hidden=YES;
        self.tickImageView03.hidden=NO;
        
//        self.tickImageView01.hidden=NO;
//        self.tickImageView02.hidden=YES;
//        self.tickImageView03.hidden=YES;
//        NSLog(@"钱包");
    }
}
- (IBAction)goBack:(id)sender
{
    //跳到指定的界面
    for (UIViewController *controller in self.navigationController.viewControllers)
    {
        if ([controller isKindOfClass:[activityOrderViewController class]])
        {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}
//确认付款,钱包num=1,微信num=2,支付宝num=3.
- (IBAction)payingTheBill:(id)sender
{
    //钱包
    if (num==1)
    {
        NSLog(@"钱包");
        [self updatePayDataFromNet];
    }//微信
    else if (num==2)
    {
        NSLog(@"微信");
    }//支付宝
    else if (num==3)
    {
        NSLog(@"支付宝");
//        [self doAlipayPay];
        [self updatePayForDataFromNet];
    }
}
//参数获取数据,下一步进行获取数据
-(void)updatePayForDataFromNet
{
    buyNSObject *bn=[buyNSObject shardeManager];
    activityOrder *ao=[activityOrder shardeManager];
    NSString*urlString=[NSString stringWithFormat:@"http://112.74.114.1/Parenting/app_alipay1/signatures_url.php"];
    NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
    parameters[@"out_trade_no"]=ao.numberString;
    parameters[@"total_fee"]=bn.all_price;
    parameters[@"subject"]=ao.subjectString;
    parameters[@"partner"]=@"2088222103001494";
    parameters[@"service"]=@"mobile.securitypay.pay";

//    NSLog(@"ao.numberString=%@",ao.numberString);
//    NSLog(@"bn.all_price=%@",bn.all_price);
//    NSLog(@"ao.subjectString=%@",ao.subjectString);

    HttpRequest *httpRequest=[HttpRequest sharedInstance];
    [httpRequest postWithURLString:urlString parameters:parameters success:^(id responseObject)
     {
         id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
         NSDictionary *data_dic=[NSDictionary dictionary];
         data_dic=[json objectForKey:@"data"];
         //标题
         NSString *bodyString=[data_dic objectForKey:@"body"];
         //描述说明
         NSString *subjectString=[data_dic objectForKey:@"subject"];
         //私钥获取
         NSString *private_key=[data_dic objectForKey:@"private_key"];
         NSString *notify_url=[data_dic objectForKey:@"notify_url"];
//         NSLog(@"bodyString=%@",bodyString);
//         NSLog(@"subjectString=%@",subjectString);
         if (data_dic.count>0)
         {
             [self doAlipayPayAndSubject:subjectString Body:bodyString private:private_key Notify_url:notify_url];
         }
//         NSLog(@"json=%@",json);
     } failure:^(NSError *error) {
         NSLog(@"error=%@",error);
     }];
}

#pragma mark   ==============发起支付==============
- (void)doAlipayPayAndSubject:(NSString *)subject Body:(NSString *)body private:(NSString *)private_Key Notify_url:(NSString *)notify_url
{
#pragma mark 以下为客户端操作 / 应在服务端操作  （下列有说明）
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = @"2016082301792262";
    NSString *seller = @"18633500076";
    NSString *privateKey = private_Key;
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    // NOTE: app_id设置
    order.app_id=appID;
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    // NOTE: 支付版本
    order.version = @"1.0";
    // NOTE: sign_type设置
    order.sign_type = @"RSA";
    // NOTE: 商品数据
    order.biz_content = [BizContent new];
    //商品标题
    order.biz_content.body = body;
    //商品描述
    order.biz_content.subject = subject;
    //*************************************************************
    //商家支付宝账号
    order.biz_content.seller_id=seller;
    //*************************************************************
    //*************************************************************
    order.notify_url=notify_url;
    //*************************************************************
    //订单ID（由商家自行制定）(后台给)
    order.biz_content.out_trade_no = [self generateTradeNO];
    //超时时间设置
    order.biz_content.timeout_express = @"30m";
    //商品价格
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", 0.01];
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    NSLog(@"orderSpec = %@",orderInfo);
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderInfo];
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"alisdkdemo";
        
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",orderInfoEncoded, signedString];
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            //在没有安装的支付宝app会走此方法
            [self goBackMainView];
            NSLog(@"reslut01 = %@",resultDic);
        }];
    }
    
}
#pragma mark ========================产生随机订单号======================
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
-(void)updatePayDataFromNet
{
    buyNSObject *bn=[buyNSObject shardeManager];
    NSString*urlString=[NSString stringWithFormat:@"http://112.74.114.1/Parenting/index.php/api/lineAction/pay"];
    NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
    parameters[@"number"]=bn.numbuerString;
    parameters[@"uid"]=userID;
    parameters[@"price"]=bn.all_price;
    parameters[@"lid"]=bn.lidString;
    parameters[@"pay"]=[NSString stringWithFormat:@"%d",
                        payNum];
    NSLog(@"payNum00=%d",payNum);
    HttpRequest *httpRequest=[HttpRequest sharedInstance];
    [httpRequest postWithURLString:urlString parameters:parameters success:^(id responseObject)
     {
         id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
         //获取数组
         NSString *msgString=[json objectForKey:@"msg"];
         int msg=[msgString intValue];
//         NSLog(@"msgString=%@",msgString);
//         //
         if (msg==400)
         {
             [self onAlertAction];
         }
        NSLog(@"json=%@",json);
     } failure:^(NSError *error) {
         NSLog(@"error=%@",error);
     }];
}
//
-(void)onAlertAction
{
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"抱歉,您的钱包余额不足" message:@"无法完成支付" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"NSLog取消");
    }];
    UIAlertAction *okAction=[UIAlertAction actionWithTitle:@"充值" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"NSLog充值");
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
-(void)goBackMainView
{
    //跳到指定的界面
    for (UIViewController *controller in self.navigationController.viewControllers)
    {
        if ([controller isKindOfClass:[homeViewController class]])
        {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
